package org.micode.libs.servlet.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.micode.common.annotation.NoNeedLogin;
import org.micode.common.annotation.PermissionsFlag;
import org.micode.common.consts.HttpHeadConsts;
import org.micode.common.domain.ApiResult;
import org.micode.common.domain.base.IUserCache;
import org.micode.common.enums.ResultEnum;
import org.micode.common.exception.DataException;
import org.micode.libs.servlet.base.AbstractWebController;
import org.micode.libs.servlet.utils.HttpContextUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 通用的处理中断类，虚类，需要通过子类继承使用。
 */
@Slf4j
public abstract class CommonWebInterceptor extends BaseAppInterceptor {

    protected boolean isValidIP(HttpServletRequest httpServletRequest) {
        return true;
    }

    @Override
    protected boolean checkPermission(HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse,
                                      Object handler) throws IOException {
        log.trace("Into CommonWebInterceptor.checkPermission() {}", handler);
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            log.trace("isAssignableFrom CommonWebInterceptor.checkPermission()");
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            if (!(handlerMethod.getBean() instanceof AbstractWebController)) {
                // 不是从 BaseController 过来的请求调用，则直接返回true
                return true;
            }

            if (!isValidIP(httpServletRequest)) {
                log.warn("The request source client IP is illegal!");
                ApiResult apiResult = new ApiResult();
                apiResult.setCode(ResultEnum.IP_INVALID.getCode());
                apiResult.setMsg(ResultEnum.IP_INVALID.getName());
                returnResult(httpServletResponse, apiResult);
                return false;
            }

            if (noNeedLogin(handlerMethod)) {
                return true;
            } else {
                if (this.userLogon(httpServletRequest)) {
                    // 用户已经登录
                    if (!isSupports(httpServletRequest, handlerMethod)) {
                        log.warn("No permission!");
                        ApiResult apiResult = new ApiResult();
                        apiResult.setCode(ResultEnum.PERMISSION_ERROR.getCode());
                        apiResult.setMsg(ResultEnum.PERMISSION_ERROR.getName());
                        returnResult(httpServletResponse, apiResult);
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    // 用户没有登录，把相关信息返回给前端处理
                    log.info("The user has not logged in!");
                    ApiResult apiResult = new ApiResult();
                    apiResult.setCode(ResultEnum.TOKEN_INVALID.getCode());
                    apiResult.setMsg(ResultEnum.UN_LOGIN.getName());
                    returnResult(httpServletResponse, apiResult);

                    return false;
                }
            }
        } else {
            return true;
        }
    }

    private boolean isSupports(HttpServletRequest httpServletRequest,
                               HandlerMethod handlerMethod) {
        PermissionsFlag permissionsFlag = handlerMethod.getMethodAnnotation(PermissionsFlag.class);
        if (permissionsFlag == null) {
            // 未设定PermissionsFlag标识, 则默认为具备使用权限
            return true;
        }

        IUserCache userAuthCache = this.getUserAuthFormCache(httpServletRequest);
        if (null != userAuthCache) {
            return checkPermissionsFlag(permissionsFlag.value(), userAuthCache);
        }

        return false;
    }

    protected boolean checkPermissionsFlag(String permissionsFlagValue, IUserCache userAuthCache) {
        // 默认是没有没有权限的
        return false;
    }

    private boolean noNeedLogin(HandlerMethod handlerMethod) {
        NoNeedLogin noNeedLogin = handlerMethod.getMethodAnnotation(NoNeedLogin.class);
        return null != noNeedLogin;
    }

    private boolean userLogon(HttpServletRequest httpServletRequest) {
        IUserCache userAuthCache = this.getUserAuthFormCache(httpServletRequest);
        return userAuthCache != null;
    }

    private IUserCache getUserAuthFormCache(HttpServletRequest request) {
        String token = HttpContextUtils.getToken(request);
        if (StringUtils.isEmpty(token)) {
            throw new DataException("Token cannot be null");
        }

        String clientApp = HttpContextUtils.getClientApp(request);
        try {
            IUserCache userAuth = getUserCacheByToken(token, clientApp);
            if (null != userAuth) {
                // 还在活跃期内
                try {
                    //将用户缓存加入请求中
                    log.trace("Put userAuth into cache, {}", userAuth);
                    request.setAttribute(HttpHeadConsts.REQUEST_USER_KEY, userAuth);
                    if (userAuth.resetExpireTime()) {
                        // 已经重设过期时间，然后放入缓存区
                        setUserCacheByToken(token, clientApp, userAuth);
                    }

                    updateUserActive(userAuth.getUserId(), clientApp);
                } catch (Exception e) {
                    log.error("Update cache exception", e);
                }
            }
            return userAuth;
        } catch (Exception e) {
            log.warn("Extract user exception from cache", e);
            return null;
        }
    }

    protected abstract void setUserCacheByToken(String token, String clientApp, IUserCache userAuth);

    protected abstract IUserCache getUserCacheByToken(String token, String clientApp);

    /**
     * 更新用户活动状态，子类中实现，这里可以做更新数据库的相关信息。
     */
    protected abstract void updateUserActive(Long userId, String clientApp);

}
